package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.admin.mapper.AdChannelMapper;
import com.usian.admin.service.AdChannelService;
import com.usian.model.admin.dtos.ChannelDto;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;


import java.util.Date;

@Service
public class AdChannelServiceImpl  extends ServiceImpl<AdChannelMapper,AdChannel> implements AdChannelService {

    @Override
    public ResponseResult findPage(ChannelDto dto) {
        //参数判断
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();

        //按照名称模糊分页查询
        Page page=new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<AdChannel> lambdaQueryWrapper =new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(dto.getName())){
            lambdaQueryWrapper.like(AdChannel::getName,dto.getName());
        }
        IPage page1 =page(page,lambdaQueryWrapper);
        //封装结果
        ResponseResult responseResult =new PageResponseResult(dto.getPage(),dto.getSize(),(int)page1.getTotal());
        responseResult.setData(page1.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult add(AdChannel adChannel) {
        //检查参数
        if (adChannel==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //保存
        adChannel.setCreatedTime(new Date());
        save(adChannel);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult edit(AdChannel adChannel) {
        //检查参数
        if (adChannel==null || adChannel.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //修改
        updateById(adChannel);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult delete(Integer id) {
        //检查参数
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断当前频道是否存在和有效
        AdChannel adChannel=getById(id);
        if (adChannel==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        if (adChannel.getStatus()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"有效不能删除");
        }
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
